package com.hb.znpt.utils;

import com.unitlib.base.utils.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;

public class AESHttpUtil {

    private final static byte[] KEY = "CHTBkvy123AYBukk".getBytes();
    private final static byte[] IV = "5123317319973153".getBytes();

    public static String 加密(String str) throws Exception {
        return URLEncoder.encode(Base64Utils.encode(AESHttpUtil.encryption(str.getBytes("UTF-8"))), "UTF-8");
    }

    public static String 解密(String str) throws Exception {
        return new String(AESHttpUtil.decryption(Base64Utils.decode(URLDecoder.decode(str, "UTF-8"))), "UTF-8");
    }

    public static byte[] encryption(byte[] data) throws Exception {
        return cipherIV(Cipher.ENCRYPT_MODE, data);
    }

    public static byte[] decryption(byte[] data) throws Exception {
        return cipherIV(Cipher.DECRYPT_MODE, data);
    }

    private static byte[] cipherIV(int mode, byte[] data) throws Exception {
        SecretKeySpec sekey = new SecretKeySpec(KEY, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(mode, sekey, new IvParameterSpec(IV));
        byte[] decrypted = cipher.doFinal(data);
        return decrypted;
    }


    @SuppressWarnings("all")
    private static byte[] cipher(int mode, byte[] data) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(mode, new SecretKeySpec(KEY, "AES"));
        byte[] decrypted = cipher.doFinal(data);
        return decrypted;
    }

    public static final String getMd5(String s) {
	  /*      char hexDigits[] = {
	            '5', '0', '5', '6', '2', '9', '6', '2', '5', 'q',
	            'b', 'l', 'e', 's', 's', 'y'
	        };
	        */
        char hexDigits[] = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F'
        };

        try {
            char str[];
            byte strTemp[] = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte md[] = mdTemp.digest();
            int j = md.length;
            str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }

            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}
